package cn.com.zzz.taskpk.tcpip;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;

import cn.bbs.ba.base.BaseDto;
import cn.bbs.ba.html.ZPaiConstant;
import cn.bbs.ba.json.JSONUntil;
import cn.bbs.ba.log.LogTrac;
import cn.bbs.ba.mi.BAMima;
import cn.bbs.ba.path.BasePath;
import cn.bbs.ba.socket.BusCodeToBusBase;
import cn.bbs.ba.util.CommonUntil;


/**
 * 监听socket服务器
 * @author xieyong
 *
 */
public class SocketThread extends Thread {
	
	private ServerSocket serverScoket=null;
	private ServletContext servletContext;
	private BusCodeToBusBase base;
	
	public SocketThread(ServerSocket serverScoket,ServletContext servletContext, BusCodeToBusBase base)
	{
		try {
			if(null==serverScoket)
			{
				this.serverScoket = new ServerSocket(CommonUntil.objToint(BasePath.getPath("socket_port")));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.servletContext=servletContext;
		this.base = base;
	}
	
	public void run()
	{
		while(!this.isInterrupted())
		{	Socket socket= null;
			try {
				socket=serverScoket.accept();
				if(null!=socket)
				{
					BufferedReader br = new BufferedReader(new InputStreamReader(socket
							.getInputStream(),"utf-8"));
					String msg = br.readLine();
					 LogTrac.info("服务器收到: " + msg);
					
					// 交易代码
					String bussinessCode = StringUtils.substring(msg, 0, 10);
					// 报文长度
					int length = CommonUntil.objToint(StringUtils.substring(msg, 10, 15));
					// 报文加密文
					String strMiwen = StringUtils.substring(msg, 15, 47);
					// JSON/EXML
					String strType = StringUtils.substring(msg, 47, 51);
					// AS3/AND/JSP
					String strCome = StringUtils.substring(msg, 51, 54);
					// 报文
					String jsonMsg = StringUtils.substring(msg, 100).trim();
					String retStr = "";
					// 如果数据长度和送来的长度不一致，则为篡改后报文。
					if(length != jsonMsg.length()) {
						retStr = ZPaiConstant.disPlay("报文格式不对，或者是报文被篡改。");
					}
//					// 判断加密后是否相同
//					else if(!strMiwen.equals(BAMima.encry(jsonMsg))) {
//						retStr = ZPaiConstant.disPlay("加密后不同，报文被篡改。");
//					}
					// 正常的时候
					else {
						BaseDto para = JSONUntil.parseJSON2Map(jsonMsg);
						// IP地址
						socket.getInetAddress().getHostAddress();
						// JSON方式 调用业务
						retStr = base.doSelectBussness(bussinessCode, para);
					}

					PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
					StringBuilder retbud = new StringBuilder();
					// 交易代码
					retbud.append(bussinessCode);
					// 报文长度
					retbud.append(StringUtils.leftPad(CommonUntil.objToString(retStr.length()), 5, "0"));
					// 报文加密文
					retbud.append(StringUtils.rightPad(BAMima.encry(retStr), 32, "0"));
					// JSON/EXML
					retbud.append(StringUtils.rightPad(strType, 4, " "));
					// 报文来源AS3/AND/JSP
					retbud.append(StringUtils.rightPad(strCome, 3, " "));
					// 预留报文头
					retbud.append(StringUtils.rightPad("0", 46, "0"));
					retbud.append(retStr);
					
					LogTrac.info("服务器返回: " + retbud.toString());
					// 传送到客户端
		            out.println(retbud.toString());
		            out.flush();
		            // 要用短连接
		            socket.close();
				}
			} catch (Exception e) {
				if(socket != null) {
					try {
						socket.close();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				e.printStackTrace();
			}
		}
	}
	
	public void closeSocketServer()
	{
			try {
				if(null!=serverScoket && !serverScoket.isClosed())
				{
					serverScoket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
}